package com.wxxymaker.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @AUTHOR soft
 * @DATE 2018/8/21 11:50
 * @DESCRIBE
 */
@Slf4j
public class IpUtils {
    public static String getLocation(String ip) {
        String[] ss = new String[2];
        String  html = new IpUtils().get(ip);
        if (html != null) {
            Matcher div = Pattern.compile("<div\\s+id=\"result\"(.*?)</div>").matcher(html);
            if (div.find()) {
                String divTag = div.group();
                Matcher code = Pattern.compile("<code>(.*?)</code>").matcher(divTag);
                for (int i = 0; i < ss.length; i++) {
                    if (code.find()) {
                        ss[i] = code.group(1);
                    }
                }
            }
        }
        return ss[1];
    }

    private String get(String ip) {
        try {
            URL url = new URL("https://ip.cn/index.php?ip=" + ip);
            URLConnection connection = url.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)");
            connection.connect();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream in = connection.getInputStream();
            int len = 0;
            byte[] bs = new byte[2048];
            while ((len = in.read(bs)) != -1) {
                out.write(bs, 0, len);
            }
            out.close();
            in.close();
            return new String(out.toByteArray());
        } catch (IOException e) {
            log.error("发送get请求失败！{}", e.getMessage());
        }
        return null;
    }
}
